<template>
  <el-card>
    <template #header>
      <div class="flex justify-between items-center">
        <span>分解需求</span>
        <div>
          <el-button type="primary" @click="toggleExpandAll">
            <Icon icon="ep:sort" class="mr-5px" />
            展开/折叠
          </el-button>
          <el-button type="primary" @click="openForm('create')">
            <Icon icon="ep:plus" />
            添加
          </el-button>
        </div>
      </div>
    </template>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
      @row-click="handleRowClick"
      highlight-current-row
      :current-row-key="selectedCellId"
    >
      <el-table-column label="功能名称" prop="name" width="250" />
      <el-table-column label="需求分解内容" prop="context" show-overflow-tooltip />
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button link type="primary" @click.stop="openForm('update', scope.row.id)">
            编辑
          </el-button>
          <el-button link type="danger" @click.stop="handleDelete(scope.row.id)">
            删除
          </el-button>
          <el-button link type="success" @click.stop="handleExtract(scope.row.id)">
            提取表
          </el-button>
          <el-button link type="warning" @click.stop="handleDecompose(scope.row.id)">
            分解
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <ProjectCellForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ProjectCellApi, ProjectCellVO } from '@/api/agent/cell'
import { handleTree } from '@/utils/tree'
import ProjectCellForm from '../../cell/ProjectCellForm.vue'

defineOptions({ name: 'DecomposedRequirementTab' })

const props = defineProps<{
  projectId: number
  selectedCellId: number | null
}>()

const emit = defineEmits(['select-cell', 'extracted-table', 'decomposed', 'open-form'])

const loading = ref(true)
const list = ref<ProjectCellVO[]>([])
const isExpandAll = ref(true)
const refreshTable = ref(true)
const formRef = ref()

const getList = async () => {
  if (!props.projectId) {
    list.value = []
    return
  }
  loading.value = true
  try {
    const res = await ProjectCellApi.getProjectCellList({
      projectId: props.projectId
    })
    list.value = handleTree(res, 'id', 'parentId')
  } catch (error) {
    console.error('获取分解需求列表失败', error)
  } finally {
    loading.value = false
  }
}

const openForm = (type: string, id?: number) => {
  emit('open-form', type, id)
}

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('是否确认删除该分解需求？')
    await ProjectCellApi.deleteProjectCell(id)
    ElMessage.success('删除成功')
    await getList()
  } catch (e) {
    /* empty */
  }
}

const handleExtract = async (cellId: number) => {
  try {
    loading.value = true
    await ProjectCellApi.extractTable(cellId)
    ElMessage.success('数据表提取任务已开始')
    emit('extracted-table')
  } finally {
    loading.value = false
  }
}

const handleDecompose = async (cellId: number) => {
  try {
    loading.value = true
    await ProjectCellApi.decomposeProjectCell(cellId)
    ElMessage.success('子需求分解任务已开始')
    emit('decomposed')
    await getList()
  } finally {
    loading.value = false
  }
}

const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  refreshTable.value = false
  nextTick(() => {
    refreshTable.value = true
  })
}

const handleRowClick = (row: ProjectCellVO) => {
  emit('select-cell', row)
}

onMounted(() => {
  getList()
})

watch(
  () => props.projectId,
  (newVal) => {
    if (newVal) {
      getList()
    } else {
      list.value = []
    }
  },
  { immediate: true }
)

defineExpose({ getList })
</script>